package com.ea.eadp.nexus.test.pageDefinition.console3;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;

import com.ea.eadp.nexus.test.common.PageOperation;
import com.ea.eadp.nexus.test.common.TestUtil;
import com.ea.eadp.nexus.test.pageDefinition.BasePage;

public class ConsoleBasePage extends BasePage {
    private String visibleElementId;

    public ConsoleBasePage(WebDriver driver, Class<?> cla, String visibleElementId) {
        super(driver, cla);
        this.visibleElementId = visibleElementId;
    }

    public void clickBlank(String xpath) {
        org.openqa.selenium.WebElement element = driver.findElement(By.xpath(xpath));
        Actions actions = new Actions(driver);
        actions.moveToElement(element).click().perform();
        TestUtil.sleep(1);
    }

    public void selectCheckBox(String elementId) {
        WebElement checkboxParent = driver.findElement(By.id(elementId)).findElement(By.xpath(".."));
        if (!checkboxParent.getAttribute("class").contains("checked")) {
            sendControllerKey('A');
        }
    }

    public void waitPageLoadCompleted() {
        PageOperation.WebDriverWait(driver, visibleElementId);
    }

    public void sendControllerKey(char controllerKey) {
        int keyCode = 0;
        switch (controllerKey) {
        case 'A':
            keyCode = 112; // F1
            break;
        case 'B':
            keyCode = 113; // F2
            break;
        case 'X':
            keyCode = 114; // F3
            break;
        case 'Y':
            keyCode = 115; // F4
            break;
        }
        triggerKeyDownEvent(keyCode);
    }

    public void sendControllerKey(org.openqa.selenium.Keys key) {
        int keyCode = 0;
        switch (key) {
        case UP:
            keyCode = 38;
            break;
        case DOWN:
            keyCode = 40;
            break;
        case LEFT:
            keyCode = 37;
            break;
        case RIGHT:
            keyCode = 39;
            break;
        case TAB:
            keyCode = 9;
            break;
        }
        triggerKeyDownEvent(keyCode);
    }

    private void triggerKeyDownEvent(int keyCode) {
        if (keyCode != 0) {
            JavascriptExecutor jse = (JavascriptExecutor) driver;
            jse.executeScript("var press = $.Event('keydown');press.which = " + keyCode + ";$(document).trigger(press);");
            TestUtil.sleep(1); // sleep 1 second to make the page response
        }
    }
}